#encoding:utf8
'''
clipboard
'''

import sys
import ctypes

#############################################################################################
class clipboard(object):
    @property
    def text(self):
        '''
        Get clipboard text if available
        '''
        # declare win32 API 
        # print 'text getter'

        user32      = ctypes.windll.user32
        kernel32    = ctypes.windll.kernel32

        if user32.OpenClipboard(0):
            CF_TEXT     = 1
            hClipMem    = user32.GetClipboardData(CF_TEXT)
            kernel32.GlobalLock.restype = ctypes.c_char_p
            value       = kernel32.GlobalLock(hClipMem)
            kernel32.GlobalUnlock(hClipMem)
            user32.CloseClipboard()

            # if format is not CF_TEXT, "value" will be None
            if value is not None:
                if hasattr(value, 'decode'):
                    value   = value.decode(sys.getfilesystemencoding())
                    # print 'decoded value= ', value
                    return value
                else:
                    print(value)
                    assert False, 'Never comes here'

    @text.setter
    def text(self, value):
        '''
        Set clipbard text
        '''
        if not isinstance(value, str) and not isinstance(value, unicode):
            raise TypeError('value should be of str type')

        # declare win32 API
        user32      = ctypes.windll.user32
        kernel32    = ctypes.windll.kernel32

        GlobalLock  = kernel32.GlobalLock
        memcpy      = ctypes.cdll.msvcrt.memcpy

        CF_TEXT     = 1
        GHND        = 66

        buffer      = ctypes.c_buffer(value.encode(sys.getfilesystemencoding()))
        bufferSize  = ctypes.sizeof(buffer)
        hGlobalMem  = kernel32.GlobalAlloc(GHND, bufferSize)
        GlobalLock.restype  = ctypes.c_void_p
        lpGlobalMem = GlobalLock(hGlobalMem)
        memcpy(lpGlobalMem, ctypes.addressof(buffer), bufferSize)
        kernel32.GlobalUnlock(hGlobalMem)
        if user32.OpenClipboard(0):
            user32.EmptyClipboard()
            user32.SetClipboardData(CF_TEXT, hGlobalMem)
            user32.CloseClipboard()
            return True
        else:
            print 'Failed to OpenClipboard'

#############################################################################################

if __name__ == '__main__':
    clip        = clipboard()
    print(clip.text)

    clip.text   = 'gbk'
    print(clip.text)

    clip.text   = u'李现民'
    print(clip.text)
